package lion.lel;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import lion.dev.fun.Fun;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年4月10日
 */
public class LelFuns {

	Map<String, Fun> funMap = new HashMap<>();

	public Object exec(String key, Object... args) throws Exception {

		Fun fun = funMap.get(key);
		if (fun != null) { return fun.exec(args); }

		return null;
	}

	public void add(String key, Fun fun) {

		funMap.put(key, fun);
	}

	public void add(String key, Method method) {

		funMap.put(key, new LelFunc(method));
	}

	public void add(String key, String method) {

		String clazz = method.substring(0, method.lastIndexOf("."));
		String methodName = method.substring(method.lastIndexOf(".") + 1);

		Class<?> c = null;
		try {
			c = Class.forName(clazz);
		} catch (ClassNotFoundException e) {
			throw new NullPointerException("class not found " + clazz);
		}
		Method me = null;
		for (Method m : c.getDeclaredMethods()) {
			if (m.getName().equals(methodName) && Modifier.isStatic(m.getModifiers())) {
				me = m;
				break;
			}
		}
		if (me == null) { throw new NullPointerException("method not found " + method); }

		funMap.put(key, new LelFunc(me));
	}

	public boolean has(String key) {

		return funMap.containsKey(key);
	}

}
